// src/services/notification.service.js
const prisma = require('../config/database');

// 通知类型常量(假设已在notification_type表中定义)
const NOTIFICATION_TYPES = {
  REVIEW_ASSIGNMENT_REMINDER: 6  // 批阅任务提醒
};

// 转换时间到东八区（UTC+8）
const formatTimeToUTC8 = (date) => {
  if (!date) return null;
  const utc8Date = new Date(date.getTime() + (8 * 60 * 60 * 1000)); // 转换为东八区时间
  const options = { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit',
    hour12: false
  };
  return utc8Date.toLocaleString('zh-CN', options);
};

// 获取当前东八区时间
const getCurrentUTC8Time = () => {
  const now = new Date();
  return new Date(now.getTime() + (8 * 60 * 60 * 1000));
};

// 计算两个时间之间的小时差（使用东八区时间）
const getHoursLeft = (endTime) => {
 // 获取当前东八区时间
 const now = getCurrentUTC8Time();
 // 直接使用end_time，不再添加8小时
 const end = new Date(endTime);
 return Math.round((end - now) / (1000 * 60 * 60));
};

// 创建系统通知
exports.createSystemNotification = async (recipientId, notificationType, content) => {
  try {
    const notification = await prisma.system_notification.create({
      data: {
        recipient_id: recipientId,
        sender_id: null,
        notification_type_id: notificationType,
        content: content,
        is_read: 0,
        create_time: getCurrentUTC8Time()
      }
    });
    
    return notification;
  } catch (error) {
    console.error('创建系统通知失败:', error);
    return null;
  }
};

// 创建批阅任务提醒通知(系统通知表)
exports.createReviewReminderNotification = async (userId, reviewAssignmentId) => {
  try {
    // 获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: userId }
    });

    if (!user) {
      console.log(`用户 ${userId} 不存在`);
      return false;
    }

    // 获取批阅任务信息
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: reviewAssignmentId }
    });

    if (!reviewAssignment) {
      console.log(`批阅任务 ${reviewAssignmentId} 不存在`);
      return false;
    }

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: reviewAssignment.examination_id }
    });

    // 计算批阅完成情况
    const completionInfo = await getCompletionInfo(reviewAssignment);

    // 计算剩余时间 - 使用东八区时间
    const hoursLeft = getHoursLeft(reviewAssignment.end_time);

    // 构建通知内容
    const content = `您的批阅任务"${examination ? examination.name : '未知考试'}"将在${hoursLeft}小时后到期，目前完成度为${Math.round(completionInfo.completionRate * 100)}%。请尽快完成剩余批阅工作。`;

    // 创建系统通知
    const notification = await this.createSystemNotification(
      userId,
      NOTIFICATION_TYPES.REVIEW_ASSIGNMENT_REMINDER,
      content
    );

    return notification;
  } catch (error) {
    console.error('创建批阅任务提醒通知失败:', error);
    return null;
  }
};


// 计算批阅任务完成情况
async function getCompletionInfo(reviewAssignment) {
  try {
    let totalCount = 0;
    let completedCount = 0;

    if (reviewAssignment.assignment_strategy === 1) {
      // 策略1: 按试卷分配
      // 获取分配的试卷数量
      const assignmentDetails = await prisma.review_assignment_detail.findMany({
        where: { 
          review_assignment_id: reviewAssignment.id,
          student_paper_id: { not: null }
        },
        select: {
          student_paper_id: true
        }
      });

      // 统计唯一的试卷ID
      const uniquePaperIds = [...new Set(assignmentDetails.map(d => d.student_paper_id))];
      totalCount = uniquePaperIds.length;

      // 统计已完成的试卷数量
      completedCount = await prisma.student_paper.count({
        where: {
          id: { in: uniquePaperIds },
          examination_status: 2  // 批阅完成状态
        }
      });
    } else if (reviewAssignment.assignment_strategy === 2) {
      // 策略2: 按题目分配
      // 统计分配的题目总数
      totalCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: reviewAssignment.id,
          paper_detail_id: { not: null }
        }
      });
      
      // 统计已完成的题目数量
      completedCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: reviewAssignment.id,
          paper_detail_id: { not: null },
          status: 1  // 已完成批阅
        }
      });
    }

    const completionRate = totalCount > 0 ? completedCount / totalCount : 0;

    return {
      totalCount,
      completedCount,
      completionRate
    };
  } catch (error) {
    console.error('计算批阅完成情况失败:', error);
    return { totalCount: 0, completedCount: 0, completionRate: 0 };
  }
}